from APP.models import Cpu,Disk,Mem, Net, Diskio, Kernel, LinuxSysctlFs, Processes, SoftInterrupts, SystemMetrics
import json
import uuid

from APP import Cpu, Disk, Mem, Net, Diskio, Kernel, LinuxSysctlFs, Processes, SoftInterrupts, SystemMetrics

from APP.database import db
from APP.database import db

def insert_data(prefix, measurement, field, value, local_time, tags, serial=None, interface=None,
                device=None, path=None, irq=None, fstype=None, mode=None, label=None):
    session = db.session()
    record = None
    if prefix:  # 当检测到异常时
        try:
            # 根据measurement类型选择模型
            if measurement == "diskio":
                record = Diskio(
                    serial=serial,
                    metric_name=field,
                    value=value,
                    timestamp_value=local_time.replace(tzinfo=None),
                )
            elif measurement == "cpu":
                record = Cpu(
                    metric_name=field,
                    value=value,
                    cpu_name=field,  # ????
                    timestamp_value=local_time.replace(tzinfo=None)
                )
            elif measurement == "mem":
                record = Mem(
                    metric_name=field,
                    value=value,
                    timestamp_value=local_time.replace(tzinfo=None)
                )
            elif measurement == "net":
                record = Net(
                    interface=interface,
                    metric_name=field,
                    value=value,
                    timestamp_value=local_time.replace(tzinfo=None)
                )
            elif measurement == "disk":
                record = Disk(
                    device=device,
                    path=path,
                    fstype=fstype,  # 新增字段
                    mode=mode,  # 新增字段
                    label=label,  # 新增字段
                    metric_name=field,
                    value=value,
                    timestamp_value=local_time.replace(tzinfo=None)
                )
            elif measurement == "kernel":
                record = Kernel(
                    metric_name=field,
                    value=value,
                    timestamp_value=local_time.replace(tzinfo=None)
                )
            elif measurement == "linux_sysctl_fs":
                record = LinuxSysctlFs(
                    metric_name=field,
                    value=value,
                    timestamp_value=local_time.replace(tzinfo=None)
                )
            elif measurement == "processes":
                record = Processes(
                    pid=tags.get("pid"),
                    user=tags.get("user"),  # 新增用户字段
                    command=tags.get("command"),  # 新增命令字段
                    metric_name=field,
                    value=value,
                    timestamp_value=local_time.replace(tzinfo=None)
                )
            elif measurement == "soft_interrupts":
                record = SoftInterrupts(
                    irq=irq,
                    metric_name=field,
                    value=value,
                    timestamp_value=local_time.replace(tzinfo=None)
                )
            elif measurement == "system_metrics":
                record = SystemMetrics(
                    metric_name=field,
                    value=value,
                    timestamp_value=local_time.replace(tzinfo=None),
                )
            session.add(record)
            session.commit()
            print(f"异常数据已存储到MySQL: {measurement}.{field}")
        except Exception as e:
            print(f"数据库写入失败: {str(e)}")
            session.rollback()


# # ===========================================警告可视化图表+已修复告警可视化==========================================================
# # 存储活跃异常的字典
# active_anomalies = {}
# # 存储正在跟踪的异常
# tracked_anomalies = {}
#
#
# # 告警可视化图表+已修复告警可视化
# def insert_alert_data(measurement, field, local_time, value, device=None, is_anomaly=False):
#     session = db.session()
#     try:
#         if not device:
#             device = "unknown_device"
#
#         # 构造复合标识符
#         alert_identifier = f"{device}_{measurement}_{field}"
#
#         # 构造事件名称
#         event_name = f"{measurement}.{field}出现异常告警"
#
#         # 拿到时间序列的数据
#         time_point = local_time.strftime("%H:%M:%S")
#
#         if is_anomaly:
#             # 如果是异常数据
#             if alert_identifier not in tracked_anomalies:
#                 # 新的异常，创建记录
#                 danger_point = {"name": f"{measurement}.{field}", "begin": local_time.strftime("%H:%M"), "end": None}
#
#                 alert_id = str(uuid.uuid4())
#                 record = DangerShow(
#                     id=alert_id,
#                     event_name=event_name,
#                     time_data=json.dumps([time_point]),  # 数组格式的时间数据
#                     value_data=json.dumps([value]),  # 数组格式的数值数据
#                     danger_data=json.dumps([danger_point]),  # 数组格式的告警时段数据
#                     work_note=None
#                 )
#
#                 # 添加到跟踪列表
#                 tracked_anomalies[alert_identifier] = {
#                     "id": alert_id,
#                     "end_time_tracking": False
#                 }
#
#                 session.add(record)
#                 session.commit()
#                 print(f"新的异常数据已存储到DangerShow表: {measurement}.{field}")
#             else:
#                 # 已存在的异常，更新数据
#                 existing_alert = DangerShow.query.get(tracked_anomalies[alert_identifier]["id"])
#                 if existing_alert:
#                     # 更新时间序列和数值序列
#                     time_data = json.loads(existing_alert.time_data) if existing_alert.time_data else []
#                     value_data = json.loads(existing_alert.value_data) if existing_alert.value_data else []
#
#                     # 检查是否已经存在相同的时间点
#                     if time_point not in time_data:
#                         time_data.append(time_point)
#                         value_data.append(value)
#
#                     # 更新数据库记录
#                     existing_alert.time_data = json.dumps(time_data)
#                     existing_alert.value_data = json.dumps(value_data)
#
#                     session.commit()
#                     print(f"异常数据已更新到DangerShow表: {measurement}.{field}")
#         else:
#             # 如果是非异常数据，检查是否在跟踪异常结束后数据
#             if alert_identifier in tracked_anomalies and not tracked_anomalies[alert_identifier]["end_time_tracking"]:
#                 # 继续收集异常结束后的数据
#                 existing_alert = DangerShow.query.get(tracked_anomalies[alert_identifier]["id"])
#                 if existing_alert:
#                     # 更新时间序列和数值序列
#                     time_data = json.loads(existing_alert.time_data) if existing_alert.time_data else []
#                     value_data = json.loads(existing_alert.value_data) if existing_alert.value_data else []
#
#                     # 检查是否已经存在相同的时间点
#                     if time_point not in time_data:
#                         time_data.append(time_point)
#                         value_data.append(value)
#
#                     # 更新数据库记录
#                     existing_alert.time_data = json.dumps(time_data)
#                     existing_alert.value_data = json.dumps(value_data)
#
#                     session.commit()
#                     print(f"异常后数据已更新到DangerShow表: {measurement}.{field}")
#
#     except Exception as e:
#         print(f"告警数据存储失败: {str(e)}")
#         session.rollback()


# 处理异常结束后继续收集10秒数据的函数
# def post_anomaly_data_collection(measurement, field, local_time, value, device=None):
#     # 调用insert_alert_data，但标记为非异常数据
#     insert_alert_data(measurement, field, local_time, value, device, is_anomaly=False)

